import { Radio, Input, Select } from 'antd'
import TextareaWithParamsV2 from '@/pages/workflow/components/TextareaWithParamsV2'
import KeyValueEditor from './KeyValueCont'
import '../index.less'
import { useSourceOptions } from '@/pages/workflow/hooks/use-source-options'
import { CommonSmallSvg } from '@/pages/workflow/components/CommonSmallTemp'
import { CommmonSmallJudgmentCommon } from '@/pages/workflow/components/CommonSmallTemp'
import { CommonSmallErrorTitle } from '@/pages/workflow/components/CommonSmallTemp'
import { useEffect, useState } from 'react'
import {CommonSmallAdddButton } from '../common'


const BodyEditor = ({ value, onChange, sourceOptions }) => {
  const { options } = useSourceOptions(sourceOptions)
  const [formContent, setFormContent] = useState([])
  useEffect(() => {
    if (value.type === 'http_form_body') {
      if (value.content?.length) {
        const newList = value.content.map(item => ({
          ...item,
          value: item.value ? item.value : undefined
        }))
        setFormContent(newList)
      } else {
        setFormContent([{ key: '', value: '', type: 'text', value_selector: [] }])
      }
    }
  }, [value.content, value.type])

  const handleChange = (newList) => {
    setFormContent(newList)
    onChange({ ...value, content: newList })
  }

  const renderFormDataContent = () => {
    return (
      <div>
        {formContent.map((item, index) => (
          <div key={index} className="flexRowStart flexRowJustBet InputCont_marTop">
            <div className="flexRowStart flexRowJustBet w-[92%]">
              <div className="w-[100px]">
                <Input
                  value={item.key}
                  onChange={e => {
                    const newList = formContent.map((obj, i) => {
                      if (i === index) {
                        return { ...obj, key: e.target.value }
                      }
                      return obj
                    })
                    handleChange(newList)
                  }}
                  placeholder="参数名称"
                />
              </div>
              <div className="inputCont_end" style={{ width: 'calc(100% - 100px)' }}>
                <Select
                  className="w-[30%]"
                  value={item.type}
                  onChange={v => {
                    const newList = formContent.map((obj, i) => {
                      if (i === index) {
                        return { ...obj, type: v, value: undefined, value_selector: [] }
                      }
                      return obj
                    })
                    handleChange(newList)
                  }}
                >
                  <Select.Option value="text">文本</Select.Option>
                  <Select.Option value="cite">引用</Select.Option>
                </Select>
                <CommmonSmallJudgmentCommon
                  item={item}
                  optionList={formContent}
                  options={options}
                  i={index}
                  Change={newList => handleChange(newList)}
                />
              </div>
            </div>
            <div className="flex items-center">
              {index === formContent.length - 1 && (
                <CommonSmallAdddButton
                  addOption={() => {
                    const newList = [...formContent, { key: '', value: '', type: 'text', value_selector: [] }]
                    handleChange(newList)
                  }}
                />
              )}
              {index > 0 && (
                <CommonSmallSvg
                  delOption={() => {
                    const newList = formContent.filter((_, i) => i !== index)
                    handleChange(newList)
                  }}
                  i={index}
                />
              )}
            </div>
          </div>
        ))}
        <CommonSmallErrorTitle
          optionList={formContent}
          noneList={['value', 'key', 'type']}
          repeat={'key'}
        />
      </div>
    )
  }

  return (
    <div>
      <Radio.Group
        value={value.type}
        onChange={e => {
          const newType = e.target.value;
          // 切换类型时重置内容
          if (['http_raw_body', 'http_json_body', 'http_xml_body'].includes(newType)) {
            onChange({ ...value, type: newType, content: '' });
          } else {
            onChange({ ...value, type: newType, content: null });
          }
        }}
        className="body-type-radio"
      >
        <Radio value="none">none</Radio>
        <Radio value="http_form_body">form-data</Radio>
        <Radio value="http_form_urlencoded_body">x-www-form-urlencoded</Radio>
        <Radio value="http_json_body">json</Radio>
        <Radio value="http_xml_body">xml</Radio>
        <Radio value="http_raw_body">raw</Radio>
      </Radio.Group>

      <div className="mt-4">
        {value.type === 'http_form_body' && renderFormDataContent()}
        {value.type === 'http_form_urlencoded_body' && (
          <KeyValueEditor
            value={value.content?.length ? value.content : [{ key: '', value: '' }]}
            onChange={content => onChange({ ...value, content })}
            info={options}
          />
        )}
        {(value.type === 'http_raw_body' || value.type === 'http_json_body' || value.type === 'http_xml_body') && (
          <TextareaWithParamsV2
            key={value.type} 
            value={value.content}  
            onChange={content => onChange({ ...value, content })}
            citeOptions={options}
          />
        )}
      </div>
    </div>
  )
}

export default BodyEditor